import 'package:dio/dio.dart';

import '../request/base_request.dart';
import 'hi_net_error.dart';
import 'hi_net_response.dart';

abstract class HiNetAdapter {
  Future<HiNetResponse<T>> send<T>(BaseRequest request);
}

/// Dio适配器
class DioAdapter extends HiNetAdapter {
  @override
  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    var options = Options(headers: request.header);
    Response? response;
    DioError? error;
    try {
      if (request.httpMethod == HttpMethod.GET) {
        response = await Dio().get(request.url, options: options);
      } else if (request.httpMethod == HttpMethod.DELETE) {
        response = await Dio().delete(request.url, data: request.params, options: options);
      } else {
        response = await Dio().post(request.url, data: request.params, options: options);
      }
    } on DioError catch (e) {
      response = e.response;
      error = e;
    }
    if (error != null) {
      //抛出HiNetError
      throw HiNetError(
        response?.statusCode ?? 404,
        error.toString(),
        data: buildResult(request, response: response),
      );
    }
    return buildResult(request, response: response);
  }

  /// 构建HiNetResponse
  HiNetResponse<T> buildResult<T>(BaseRequest request, {Response? response}) {
    return HiNetResponse(
      data: response?.data,
      statusCode: response?.statusCode,
      statusMessage: response?.statusMessage,
      extra: response,
      request: request,
    );
  }
}
